package com.android.telephonecall;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.android.telephonecall.event.MqttDataEvent;
import com.android.telephonecall.event.MqttToastEvent;
import com.android.telephonecall.utils.DeviceInfoManager;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.greenrobot.eventbus.EventBus;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * mqtt连接收发消息管理
 */
public class MqttClientManager {

    private static final String TAG = "MqttClientManager";

    public String HOST = "tcp://110.53.246.133:1883";//服务器地址（协议+地址+端口号）

    //订阅/响应主题
    public static String PUBLISH_TOPIC = "cellphone/service";
    public static String RESPONSE_TOPIC = "cellphone/response/device/";
    public static String COMMAND_TOPIC = "cellphone/device/";

    public String mDeviceId = "deviceId";  //客户端ID

    private MqttClient mClient;
    private MqttConnectOptions mOptions;

    private ScheduledExecutorService mScheduler;
    private Handler mHandler;

    private static volatile MqttClientManager sClientManager;

    public static MqttClientManager getInstance() {
        if (sClientManager == null) {
            synchronized (MqttClientManager.class) {
                if (sClientManager == null) {
                    sClientManager = new MqttClientManager();
                }
            }
        }
        return sClientManager;
    }

    private MqttClientManager() {
        mqttInit();
    }

    private void mqttInit() {
        init();
        startReconnect();
        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                int code = msg.what;
                Log.d(TAG, "code->" + code);
                if (code == 3) {
                    String message = msg.obj.toString();
                    Log.d(TAG, "message->" + message);
                    EventBus.getDefault().post(new MqttDataEvent(message));
                } else if (code == 30) {
                    EventBus.getDefault().post(new MqttToastEvent(false,"连接失败"));
                } else if (code == 31) {
                    EventBus.getDefault().post(new MqttToastEvent(true,"连接成功"));
                    try {
                        mClient.subscribe(RESPONSE_TOPIC + mDeviceId, 1);
                        mClient.subscribe(COMMAND_TOPIC + mDeviceId, 1);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    private void init() {
        try {
            mDeviceId = DeviceInfoManager.getInstance().getDeviceId();
            Log.d(TAG, "init mDeviceId: " + mDeviceId);

            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            mClient = new MqttClient(HOST, mDeviceId,
                    new MemoryPersistence());
            //MQTT的连接设置
            mOptions = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            mOptions.setCleanSession(false);
            // 设置超时时间 单位为秒
            mOptions.setConnectionTimeout(30);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            mOptions.setKeepAliveInterval(30);
            mOptions.setUserName("telephone");
            mOptions.setPassword("16c88ec7-4966-c35f-51b2-56a2af86388e".toCharArray());
            //设置回调
            mClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    Log.d(TAG, "connectionLost-->");
                    startReconnect();
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    Log.d(TAG, "deliveryComplete-->" + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message) {
                    //subscribe后得到的消息会执行到这里面
                    disposeMessage(topicName, message.getPayload());

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理接收到的消息
     *
     * @param topic   主题
     * @param payload 内容
     */
    private void disposeMessage(String topic, byte[] payload) {
        // 把消息传入消息处理中心
        String msg = new String(payload, StandardCharsets.UTF_8);
        Log.d(TAG, "disposeMessage topic: " + topic + " msg:" + msg);
        Message message = new Message();
        message.what = 3;
        message.obj = msg;
        mHandler.sendMessage(message);
    }

    //重连
    private void startReconnect() {
        mScheduler = Executors.newSingleThreadScheduledExecutor();
        mScheduler.scheduleAtFixedRate(() -> {
            if (!mClient.isConnected()) {
                MqttConnect();
            }
        }, 0, 5 * 1000, TimeUnit.MILLISECONDS);
    }

    //连接
    private void MqttConnect() {
        new Thread(() -> {
            try {
                if (!(mClient.isConnected()))  //如果还未连接
                {
                    mClient.connect(mOptions);
                    Message msg = new Message();
                    msg.what = 31;
                    mHandler.sendMessage(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Message msg = new Message();
                msg.what = 30;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    /**
     * 发送消息
     * @param topic 主题
     * @param message2 消息内容
     */
    public void publishMessage(String topic, byte[] message2, String type) {
        if (mClient == null || !mClient.isConnected()) {
            return;
        }
        try {
            Log.d(TAG, "publishMessage topic: " + topic + " message2:" + message2
                    + " type:" + type);
            mClient.publish(topic, message2,1, false);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}
